<?php

namespace app\command\tasks;

use app\helper\Log;
use app\common\services\EnergyService;
use app\common\repositories\energy\EnergyMeterRepository;
use app\common\repositories\energy\EnergyMeterDayRepository;

/**
 * 电表日冻结
 * Class ElectricDayFreezeReadingTask
 *
 * @package app\command\task
 */
class EnergyDayFreezeReadingTask
{

    protected function writeLog($str)
    {
        Log::writeLog('查询电表日冻结', $str, false);
    }

    /**
     * 执行任务
     * @return mixed
     */
    public function execute()
    {
        /** @var EnergyMeterRepository $energyMeterRepository */
        $energyMeterRepository = app()->make(EnergyMeterRepository::class);
        /** @var EnergyMeterDayRepository $energyMeterDayRepository */
        $energyMeterDayRepository = app()->make(EnergyMeterDayRepository::class);

        $sql = $energyMeterDayRepository->getSearch([])
            ->alias('emd')
            ->whereRaw('emd.energy_id = em.id')
            ->where('emd.day_time', date('Y-m-d', strtotime('-1 day')))
            ->fetchSql(true)
            ->select();

        $this->writeLog('开始查询');
        try {
            $energyMeterRepository->getSearch([])->alias('em')
                ->whereRaw("NOT EXISTS ({$sql})")
                ->where('em.wit_type', 1)
                ->field('id,energy_no')
                ->chunk(100, function ($meterList) use ($energyMeterRepository) {
                    $address = get_arr_column($meterList, 'energy_no');
                    $startDate = $endDate = date('Y-m-d', strtotime('-1 day'));
                    $server = EnergyService::init(1)->Electric()->queryElectricMeterDayFreeze($startDate, $endDate);
                    $server->setmeter_address($address);
                    $res = $server->execute();
                    if ($res && $res['code'] == 200) {
                        $dayList = $res['data']['list'] ?? [];
                        $dayList = convert_arr_key($dayList, 'meter_address');
                        foreach ($meterList as $k => $v) {
                            $dayInfo = $dayList[$v['energy_no']] ?? [];
                            if ($dayInfo) {
                                $data = [
                                    'read_z' => $dayInfo['reading'],
                                    'read_j' => $dayInfo['max_reading'],
                                    'read_f' => $dayInfo['peak_reading'],
                                    'read_p' => $dayInfo['usual_reading'],
                                    'read_g' => $dayInfo['min_reading']
                                ];
                                $energyMeterRepository->taskMeterReadingHandle($v['id'], $data, $dayInfo['use_time']);
                            }
                        }
                    }
                });
            $this->writeLog('查询成功');
        } catch (\Exception $e) {
            exception_log('查询电表日冻结数据失败', $e);
            $this->writeLog('查询失败');
        }
    }

}
